package com.handydata.antifraud.ws.dap;

import java.util.Date;
import java.util.UUID;

import javax.annotation.PostConstruct;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.handydata.antifraud.annotation.Comment;
import com.handydata.antifraud.bo.dataBaiRongInfo.DataBaiRongInfoReqBO;
import com.handydata.antifraud.bo.datacalllogs.DataCallLogsReqBO;
import com.handydata.antifraud.common.constant.DataSourceCode;
import com.handydata.antifraud.service.DataBaiRongInfoService;
import com.handydata.antifraud.service.DataCallLogsService;
import com.handydata.antifraud.to.dap.BRDebtRepayStressReqTO;
import com.handydata.antifraud.to.dap.BRDebtRepayStressResTO;
import com.handydata.antifraud.util.DateUtil;
import com.handydata.antifraud.util.encrypt.Md5Utils;
import com.handydata.antifraud.ws.WsInvocationService;

/**
 * 百融偿债压力指数
 */
@Slf4j
@Service("bRDebtRepayStressWsService")
@Comment("百融偿债压力指数")
public class BRDebtRepayStressWsServiceImpl extends
		DataPlatformWsService<BRDebtRepayStressReqTO, BRDebtRepayStressResTO> implements
		WsInvocationService<BRDebtRepayStressReqTO, BRDebtRepayStressResTO> {

	@Autowired
	private DataCallLogsService dataCallLogsService;
	@Autowired
	private DataBaiRongInfoService dataBaiRongInfoService;

	@Override
	public BRDebtRepayStressResTO query(BRDebtRepayStressReqTO req) {
		log.info("百融偿债压力指数请求参数 {}", req);
		BRDebtRepayStressResTO resTO = new BRDebtRepayStressResTO();
		if (StringUtils.isEmpty(req.getIdCard())) {
			log.error("百融偿债压力指数参数校验 {}", "cid为空");
			resTO.setResCode("1111");
			resTO.setResMsg("百融偿债压力指数接口cid参数为空");
			return resTO;
		}
		if (StringUtils.isEmpty(req.getName())) {
			log.error("百融偿债压力指数参数校验 {}", "name为空");
			resTO.setResCode("1111");
			resTO.setResMsg("百融偿债压力指数接口name参数为空");
			return resTO;
		}
		if (StringUtils.isEmpty(req.getPhoneNum())) {
			log.error("百融偿债压力指数参数校验 {}", "phoneNum为空");
			resTO.setResCode("1111");
			resTO.setResMsg("百融偿债压力指数接口phone参数为空");
			return resTO;
		}
		this.dataType = DataSourceCode.BAI_RONG.getCode();
		long startDate = new Date().getTime();
//		handleRequestParam(req);
		try {
			resTO = executeQuery(req);
			long endDate = new Date().getTime();
			int aa = Integer.valueOf(String.valueOf((endDate - startDate)));
			DataCallLogsReqBO dataCallLogsReqBO = new DataCallLogsReqBO();
			dataCallLogsReqBO.setId(UUID.randomUUID().toString().replace("-", ""));
			dataCallLogsReqBO.setParams(JSONObject.toJSONString(req));
			dataCallLogsReqBO.setElapsed(aa);
			dataCallLogsReqBO.setWselapsed(aa);
			dataCallLogsReqBO.setId(UUID.randomUUID().toString().replace("-", ""));
			dataCallLogsReqBO.setOrderId(req.getOrderId());
			dataCallLogsReqBO.setDataType(DataSourceCode.BAI_RONG.getCode());
			dataCallLogsReqBO.setResult(resTO.getResData());
			dataCallLogsReqBO.setResCode(resTO.getResCode());
			dataCallLogsReqBO.setResMsg(resTO.getResMsg());
			dataCallLogsReqBO.setCreateTime(new Date());
			dataCallLogsReqBO.setUpdateTime(new Date());
			dataCallLogsService.createDataCallLogs(dataCallLogsReqBO);
		} catch (Exception e) {
			DataBaiRongInfoReqBO dataBaiRongInfoReqBO = new DataBaiRongInfoReqBO();
			dataBaiRongInfoReqBO.setOrderId(req.getOrderId());
			dataBaiRongInfoReqBO.setResCode("9999");
			dataBaiRongInfoReqBO.setResMsg("百融接口调用异常");
			dataBaiRongInfoReqBO.setCreateTime(new Date());
			dataBaiRongInfoService.createDataBaiRongInfo(dataBaiRongInfoReqBO);
			resTO.setResCode("9999");
			resTO.setResMsg("百融接口调用异常");
		}
		return resTO;
	}

	@Override
	protected String createQueryXml(BRDebtRepayStressReqTO req) {
		StringBuilder xml = new StringBuilder();
		xml.append("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>");
		xml.append("<subatm>");
		xml.append("<application>GwBiz.Req</application>");
		xml.append("<version>1.0.0</version>");
		xml.append("<sendTime>").append(DateUtil.now14()).append("</sendTime>");
		xml.append("<transCode>101013</transCode>");
		xml.append("<channelId>").append(encryInfo.getChannelId()).append("</channelId>");
		xml.append("<channelOrderId>").append(DateUtil.now17()).append("</channelOrderId>");
		xml.append("<name>").append(Md5Utils.md5ToHexStr(req.getName())).append("</name>");
		xml.append("<cid>").append(Md5Utils.md5ToHexStr(req.getIdCard())).append("</cid>");
		xml.append("<phone>").append(Md5Utils.md5ToHexStr(req.getPhoneNum())).append("</phone>");
		xml.append("<contactsPhone>").append(req.getContactsPhone()).append("</contactsPhone>");
		xml.append("<yearRange>").append(req.getYearRange()).append("</yearRange>");
//		xml.append("<queryModule>ApplyLoanStr,SpecialList_c,FraudRelation_g,DebtRepayStress,ExecutionLimited,GrayListExpand</queryModule>");
		xml.append("<queryModule>DebtRepayStress</queryModule>");
		xml.append("</subatm>");
		log.info("百融接口调用翰迪数据平台请求报文：{}", xml);
		req.setQueryXml(xml.toString());
		return xml.toString();
	}

	@Override
	protected BRDebtRepayStressResTO parseResultAndSave(String resultXml, String orderId,	Date createDate) {
		log.info("调用百融偿债压力指数接口返回报文：{}", resultXml);
		BRDebtRepayStressResTO resTO = new BRDebtRepayStressResTO();
		JSONObject resObject = new JSONObject();
		// 百融数据入库
		DataBaiRongInfoReqBO dataBaiRongInfoReqBO = new DataBaiRongInfoReqBO();
		dataBaiRongInfoReqBO.setOrderId(orderId);
		try {
			// 解析xml，保存本地DB
			JSONObject jasonObject = JSONObject.parseObject(resultXml);
			if (null != jasonObject) {
				if ("0000".equals(jasonObject.get("resCode"))) {
					JSONObject resData = (JSONObject) jasonObject.get("resData");
					JSONObject flagJsonObject = (JSONObject) resData.get("Flag");
					// 百融入库参数
					dataBaiRongInfoReqBO.setResCode(jasonObject.getString("resCode"));
					dataBaiRongInfoReqBO.setResMsg(jasonObject.getString("resMsg"));
					dataBaiRongInfoReqBO.setFlag(resData.getString("Flag"));
					dataBaiRongInfoReqBO.setApplyLoanStr(resData.getString("ApplyLoanStr"));
					dataBaiRongInfoReqBO.setSpecialListC(resData.getString("SpecialList_c"));
					dataBaiRongInfoReqBO.setFraudRelationG(resData.getString("FraudRelation_g"));
					dataBaiRongInfoReqBO.setDebtRepayStress(resData.getString("DebtRepayStress"));
					dataBaiRongInfoReqBO.setExecutionLimited(resData.getString("ExecutionLimited"));
					dataBaiRongInfoReqBO.setGrayListExpand(resData.getString("GrayListExpand"));
					dataBaiRongInfoReqBO.setCreditModelEvaC(resData.getString("CreditModelEva_c"));
					
					// 偿债压力指数
					if (StringUtils.isNotBlank(flagJsonObject.getString("debtrepaystress")) && 
							flagJsonObject.getInteger("debtrepaystress") == 1) {
						JSONObject debtRepayStress = (JSONObject) resData.get("DebtRepayStress");
						if (StringUtils.isNotEmpty(debtRepayStress.getString("nodebtscore"))) {
							double brDebtscore = Double.parseDouble(debtRepayStress.getString("nodebtscore"));//百融-偿债压力指数
							resObject.put("br_debtscore", brDebtscore);
							resTO.setBrDebtscore(brDebtscore);
						} else {
							resObject.put("br_debtscore", "9999");
						}
					} else {
						resObject.put("br_debtscore", "9999");
					}
				} else {
					// 百融入库数据
					dataBaiRongInfoReqBO.setResCode(jasonObject.getString("resCode"));
					dataBaiRongInfoReqBO.setResMsg(jasonObject.getString("resMsg"));
					resObject.put("br_debtscore", "9999");
				}
				resTO.setResCode((String) jasonObject.get("resCode"));
				resTO.setResMsg((String) jasonObject.get("resMsg"));
			} else {
				// 百融入库参数
				dataBaiRongInfoReqBO.setResCode("9999");
				dataBaiRongInfoReqBO.setResMsg("百融接口返回数据异常");
				
				resObject.put("br_debtscore", "9999");
				resTO.setResCode("1111");
				resTO.setResMsg("百融偿债压力指数接口返回数据异常");
			}
		} catch (Exception e) {
			log.info("调用百融偿债压力指数接口异常：{}", e);
			resTO.setResCode("1111");
			resTO.setResMsg("调用百融偿债压力指数接口异常");
			resObject.put("br_debtscore", "9999");
			// 百融入库参数
			dataBaiRongInfoReqBO.setResCode("9999");
			dataBaiRongInfoReqBO.setResMsg("百融接口返回数据异常");
		}
		dataBaiRongInfoReqBO.setCreateTime(new Date());
		dataBaiRongInfoService.createDataBaiRongInfo(dataBaiRongInfoReqBO);
		resTO.setResData(resObject.toString());
		log.info("调用百融偿债压力指数接口返回结果：{}", JSONObject.toJSONString(resTO));
		return resTO;
	}

	@SuppressWarnings("unchecked")
	@PostConstruct
	@Override
	public void register() {
		registerToWsServiceFactory(this, BRDebtRepayStressReqTO.class);
	}
 
	private void handleRequestParam(BRDebtRepayStressReqTO req) {
		String attr = req.getAttr();
		switch (attr) {
		case "唯品会":
			req.setQueryModule("SpecialList_c,ExecutionLimited");
			break;
		case "苏宁":
			req.setQueryModule("SpecialList_c,ExecutionLimited");
			break;
		case "分期乐":
			req.setQueryModule("SpecialList_c,FraudRelation_g,ExecutionLimited");
			break;	
		case "大额":
			req.setQueryModule("SpecialList_c,FraudRelation_g,DebtRepayStress,ApplyLoanStr,ExecutionLimited");
			break;		
		default:
			req.setQueryModule("SpecialList_c");
			break;
		}
		
	}
	
}
